import { ReqUser } from '@common/auth';
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, ObjectId } from 'mongoose';
import { FocusUserFocusDto } from './dto/focus-userFocus.dto';
import { ListUserFocusDto } from './dto/list-userFocus.dto';
import { UserFocus, UserFocusDocument } from './schemas/userFocus.schema';
import { Photos, PhotosDocument } from '@api/photos/schemas/photos.schema';

@Injectable()
export class UserFocusService {
    constructor(
        @InjectModel(UserFocus.name) private userFocusModel: Model<UserFocusDocument>,
        @InjectModel(Photos.name) private photosModel: Model<PhotosDocument>
    ) {}

    async focus(input: FocusUserFocusDto, reqUser: ReqUser) {
        const entity = new this.userFocusModel(input);
        entity.user = reqUser._id;
        const res = await entity.save();
        return res;
    }
    async unfocus(input: FocusUserFocusDto, reqUser: ReqUser) {
        return this.userFocusModel
            .findOneAndRemove({
                beFocusUser: input.beFocusUser,
                user: reqUser._id,
            })
            .exec();
    }
    async list(dto: ListUserFocusDto, reqUser: ReqUser) {
        const { page = 0, psize = 20 } = dto.limit || {};
        let result = [];
        if (dto.where.beFocusUser) {
            const res = await this.userFocusModel
                .find({ beFocusUser: dto.where.beFocusUser })
                .populate({ path: 'user', select: 'nickname avatar desc' })
                .skip(page * psize)
                .limit(psize)
                .sort('-createdAt')
                .exec();
            result = res.map(it => it.user);
        } else if (dto.where.user) {
            const res = await this.userFocusModel
                .find({ user: dto.where.user })
                .populate({ path: 'beFocusUser', select: 'nickname avatar desc' })
                .skip(page * psize)
                .limit(psize)
                .sort('-createdAt')
                .exec();
            result = res.map(it => it.beFocusUser);
        } else {
            throw new BadRequestException('参数错误！！');
        }
        const [photosCount, fansCount, focus] = await Promise.all([
            Promise.all(
                result.map(it => {
                    return this.photosModel.count({ user: it._id }).exec();
                })
            ),
            Promise.all(
                result.map(it => {
                    return this.userFocusModel.count({ beFocusUser: it._id }).exec();
                })
            ),
            Promise.all(
                result.map(it => {
                    return this.userFocusModel
                        .findOne({ user: reqUser._id, beFocusUser: it._id }, '_id')
                        .exec();
                })
            ),
        ]);

        return result.map((it, index) => {
            const item = { ...it.toObject() };
            item.photosCount = photosCount[index];
            item.fansCount = fansCount[index];
            item.currentUserIsFocus = Boolean(focus[index]);
            return item;
        });
    }
}
